﻿using System;
using System.Xml;
using System.Collections.ObjectModel;
using System.Collections.Specialized;

namespace Builderator.Core
{
    public class VariableDictionary : ObservableCollection<Variable>
    {
        public VariableDictionary()
            : base()
        {

        }

        public VariableDictionary(string settings)
            : this()
        {
            XmlDocument xmlDoc = new XmlDocument();

            if (settings == string.Empty)
                return;

            xmlDoc.LoadXml(settings);

            Variable variable;
            XmlElement rootElement = xmlDoc.DocumentElement;

            foreach (XmlElement child in rootElement.ChildNodes)
            {
                variable = new Variable(child.OuterXml);

                this.Add(variable);
            }
        }

        public void Add(VariableDictionary variables)
        {
            foreach (Variable variable in variables)
            {
                if (!this.Contains(variable.Name))
                    this.Add(variable);
            }
        }

        public bool Contains(string name)
        {
            foreach (Variable variable in this)
            {
                if (variable.Name == name)
                    return true;
            }

            return false;
        }

        public void Update(string name, string value)
        {
            foreach (Variable variable in this)
            {
                if (variable.Name == name)
                {
                    variable.Value = value;
                }
            }
        }

        public Variable Find(string name)
        {
            foreach (Variable variable in this)
            {
                if (variable.Name == name)
                    return variable;
            }

            return null;
        }

        public override string ToString()
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlDocumentFragment childElement;
            XmlElement rootElement = xmlDoc.CreateElement("VariableList");

            foreach (Variable var in this)
            {
                childElement = xmlDoc.CreateDocumentFragment();

                childElement.InnerXml = var.ToString();

                rootElement.AppendChild(childElement);
            }

            xmlDoc.AppendChild(rootElement);

            return xmlDoc.InnerXml;
        }
    }
}